<?php
define('AWS_API_KEY', 'AKIAI7A2EP2ETRXV4MVQ');
define('AWS_API_SECRET_KEY', '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');
define('AWS_ASSOCIATE_TAG', ' brysatt-20');

/**
 * Description of Scanner
 *
 * @author Thomas Vo
 */
class BRScanner extends CComponent
{
    public $amazonSearchUrl = 'http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=';
    public $keywords;
    private $amazonECS;
    private $response;
    private $results;
    
    const   RESULTS_PER_VIEW = 5;
    public function __construct($keywords = null) 
    {
        if(isset($keywords)) $this->keywords = $keywords;
        $this->setAmazonECS($this->createNewAmazonECS());
    }
    
    /**
     *
     * @return \AmazonECS 
     */
    public function getAmazonECS()
    {
        return $this->amazonECS; 
    }
    
    /**
     *
     * @param AmazonECS $amazonECS 
     */
    public function setAmazonECS(AmazonECS $amazonECS)
    {
        $this->amazonECS = $amazonECS;
    }
    
    public function getResponse()
    {
        $this->response;
    }
    
    /**
     *
     * @param mixed $response
     * @return \SearchResults 
     */
    public function getResults($response = null)
    {
        if($response)
        {
            if(!is_array($results = $response->Items->Item))
                $results = array($results);
            
            return new SearchResults($results);
        }
        else 
        {
            $this->results = $this->getResults($this->response);
            return $this->results;
        }
    }
    
    /**
     *
     * @return \AmazonECS 
     */
    public function createNewAmazonECS()
    {
        return new AmazonECS(AWS_API_KEY, AWS_API_SECRET_KEY, 'com', AWS_ASSOCIATE_TAG);
    }
    
    public function getErrors($response = null)
    {
        $response = $response ? $response : $this->response;
        return isset($response->Errors) ? $response->Errors : null;
    }
    
    public function errorsToHtml($errors)
    {
        $result = '';
        foreach($errors as $error)
        {
            $result .= '<p>';
            $result .= '<strong>'.$error->Code.'</strong></br>';
            $result .= $error->Message;
            $result .= '</p>';
        }
        return $result;
    }
   
    public function retrieveSearchResponse($keywords = null, $return = false)
    {
        $response = $this->getAmazonECS()
            ->category('Books')
            ->responseGroup('Medium')
            ->search($keywords ? $keywords : $this->keywords);
        
        if($return)
            return $response;
        else
            $this->response = $response;
        
    }
    
    public function search()
    {
        $response  = $this->retrieveSearchResponse();
        if($errors = $this->getErrors())
            return $this->errorsToHtml($errors);
//        throw new Exception(print_r($response,true ));
//        throw new Exception(print_r($response->Items->Item[0],true));
        $html = '';
//        throw new Exception(print_r($this->getResults()->current(),true ));
        foreach($this->getResults()->current() as $result)
            $html .= $this->productToHtml($result);
        
        return $html;
        
    }
    
    public function productToHtml($product)
    {
        $result  = '<p>';
        $result .= '<code>';
        $result .= 'title: <a href="#">'.$product->ItemAttributes->Title.'</a></br>';
        $result .= isset($product->SalesRank) ? 'rank:&nbsp&nbsp<strong>'.number_format(floatval($product->SalesRank)).'</strong></br>' : null;
        $result .= isset($product->OfferSummary->LowestNewPrice->FormattedPrice) ? 'new:&nbsp&nbsp&nbsp<strong>'. $product->OfferSummary->LowestNewPrice->FormattedPrice.'</strong></br>'  : null;
        $result .= isset($product->OfferSummary->LowestUsedPrice->FormattedPrice) ? 'used:&nbsp&nbsp<strong>'. $product->OfferSummary->LowestUsedPrice->FormattedPrice.'</strong></br>' : null;

        if(is_array($author = $product->ItemAttributes->Author))
            $author = implode(', ', $author);

        $result .= 'author: '.$author.'</br>';
        $result .= 'binding: '.$product->ItemAttributes->Binding;
        $result .= '</code>';
        $result .= '</p>';
        
        return $result;
    }
    
    
}

class SearchResults implements Iterator
{
    const INCREMENT = 5;
    private $position = 0;
    private $results  = array();
    
    public function __construct($results) {
        $this->results = $results;
    }
    
    public function current() 
    {
        return $this->valid() ? array_slice($this->results, $this->position, self::INCREMENT) : null;
    }
    
    public function key() 
    {
        return $this->position;
    }
    
    public function prev()
    {
        $this->position -= self::INCREMENT;
    }
    
    public function next() 
    {
        $this->position += self::INCREMENT;
    }
    
    public function rewind() 
    {
        $this->position = 0;
    }
    
    public function valid() 
    {
        return $this->position <= count($this->results);
    }
}
?>
